package cn.stronglink.asset.module.dam.service;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cn.stronglink.asset.message.mq.dam.RealTimeDatasMsgReceiver;
import cn.stronglink.asset.model.SensorSetting;
import cn.stronglink.asset.module.dam.entity.dev.RackInfo;
import cn.stronglink.asset.module.dam.entity.message.MsgRealTimeDatas;
import cn.stronglink.asset.module.dam.interfaces.RealtimeDatasHandleStrategyI;
import cn.stronglink.asset.module.dam.mapper.DamSensorMapper;
import cn.stronglink.asset.module.dam.utils.dataJsonUtils.realtime.receive.IntercepterRealTimeDatasUtil;
import cn.stronglink.asset.module.dam.utils.dataJsonUtils.realtime.receive.ListContainerUtil;
import cn.stronglink.asset.module.dam.utils.dataJsonUtils.realtime.send.SendOtherMsgUtils;

@Component("toSensorDbService")
public class RealTimeSendToSenDb implements RealtimeDatasHandleStrategyI {
	// 共6个传感器实时数据 + 2个list存放sensro温湿度 + 2个list存放cabinet门数据
	private ListContainerUtil listContainer = new ListContainerUtil();

	@Autowired
	private DamSensorMapper damSensorMapper;
	private RackInfo rackinfo;

	@Override
	public void handleDamDatas(MsgRealTimeDatas realDatas) {


		listContainer.clearAllSensor();// 清空容器
		synchronized (this) {
			SensorSetting[] senList = realDatas.getAwsPostdata().getSensorList();
			rackinfo = damSensorMapper.getRackInfo(realDatas.getAwsPostdata().getRackConverCode());
			long rackId = rackinfo.getRackId();

			// 查询传感器信息： 是否已存在
			if (rackId == 0) {
				System.out.println("查询..无此机柜, 无效的rackConverCode");
				return;
			}

			// 存在该机柜,更新数据
			for (SensorSetting sen : senList) {
				sen.setAssetId(rackId);// 获取sensorType: 判断是哪个传感器的数据

				// 判断是否已存在此数据记录 id
				SensorSetting selectedSensor = damSensorMapper.getSensorCountByAssetIdSensorTypePosition(sen);
				System.out.println("查询到的sensor数量" + selectedSensor.getSensorCount());

				if (selectedSensor.getSensorCount() != 0) {// 更新
					sen.setUpdateTime(new Date());
					listContainer.getSenUplist().add(sen);
				} else {// 插入记录
					sen.setCreateTime(new Date());
					listContainer.getSenInlist().add(sen);
				}
			} // for结束

			// 批量更新或增加
			if (listContainer.getSenInlist().size() > 0) {// sen表： 插入
				damSensorMapper.insertSensor(listContainer.getSenInlist());
				System.out.println("插入sen结束。。。。。。\n");
			}
			if (listContainer.getSenUplist().size() > 0) {
				damSensorMapper.updateSensor(listContainer.getSenUplist());
				System.out.println("更新sen结束。。。。。。\n");
			}
		}

	}

	@Override
	public boolean isHandle(MsgRealTimeDatas realDatas) {
		SensorSetting[] senArr = realDatas.getAwsPostdata().getSensorList();

		for (SensorSetting sen : senArr) {
			if (sen.getSensorType() != 3) {// 判断温湿度表
				return true;
			}
		}
		return false;
	}
}
